package com.zyh.flink.day05;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.functions.RuntimeContext;
import org.apache.flink.api.common.state.ReducingState;
import org.apache.flink.api.common.state.ReducingStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class StateQueryableJob {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<String> hadoop10 = env.socketTextStream("hadoop10", 9999);
        KeyedStream<Tuple2<String, Integer>, String> keyedStream = hadoop10.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String s, Collector<Tuple2<String, Integer>> collector) throws Exception {
                String[] ss = s.split("\\s+");
                for (String s1 : ss) {
                    collector.collect(Tuple2.of(s1, 1));
                }
            }
        }).keyBy(t -> t.f0);

        SingleOutputStreamOperator<Tuple2<String, Integer>> result = keyedStream.map(new RichMapFunction<Tuple2<String, Integer>, Tuple2<String, Integer>>() {
            private ReducingState<Integer> reducingState;

            @Override
            public void open(Configuration parameters) throws Exception {
                RuntimeContext context = getRuntimeContext();
                ReducingStateDescriptor<Integer> rsd = new ReducingStateDescriptor<>("rsd", (v1, v2) -> v1 + v2, Types.INT);
                //通过setQueryable方法，设置这个状态是可查询的状态
                rsd.setQueryable("queryable-word-count");
                reducingState = context.getReducingState(rsd);
            }

            @Override
            public Tuple2<String, Integer> map(Tuple2<String, Integer> value) throws Exception {
                reducingState.add(1);
                Integer count = reducingState.get();
                return Tuple2.of(value.f0, count);
            }
        });

        result.print();

        env.execute("QueryableStateJob");
    }
}
